<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<jsp:include page="/WEB-INF/views/layouts/header.jsp"/>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// 网站地址
String netPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
%>
<script type="text/javascript"> 
function initForm(){
	var form = $('.zzjg > table:eq(0)');
	var addBtn = $('.zzjg .addpost');
	var postItem = '<tr>\
	<td><p>职位{count}：</p></td>\
	<td><input type="text" class="input_cls" data-required="false" name="positionList[{count-1}].name" > <input type="checkbox" name="positionList[{count-1}].isLeader" value="Y"><input type="hidden" name="positionList[{count-1}].positionIndex" value="{count-1}" > 是否为责任人</td>\
	</tr>';
	var count = 3;
	addBtn.click(function(){
		var newTr = $(postItem.replaceAll('{count}',++count).replaceAll('{count-1}',count-1)).appendTo(form);
		var lastTd = newTr.find('td:last');
		addBtn.appendTo(lastTd);
	});
}

function bindList(){
	
	var departmentSelect = $('.zzjg .departmenu_td').html();
	var postItem = '<tr><td><p>职位{count}：</p></td><td><input type="text" name="positionList[{count-1}].name"  class="input_cls"> <input type="checkbox" name="positionList[{count-1}].isLeader" value="Y"> 是否为责任人</td></td></tr>';
	
	$('.cjbm tr').each(function(i,el){
		$('.editbtn',el).click(function(event){
			event.preventDefault();
			var defineId = $('.defineId',el).text()
			var fatherDept = $('.fatherDept',el).text()
			var department = $('.first_line',el).text();
			var postArray =  $('.post_list b',el);
			var postCount = postArray.length;
			var HTML = '<div class="Popup">';
			HTML += '<div class="Popupheader"><a node-type="close" href="#"><img src="<%=basePath%>images/Popupclose01.png" width="28" height="28"></a></div>';
			HTML += '<div class="Popup_A"><div class="Popup_A_1">';
			HTML += '<div class="Popup_title">修改部门信息</div>';
			HTML += '<table class="cjxbm">';	
			//部门名称
			HTML += '<tr><td width="23%"><p><input type="hidden" name="department.departmentId" value="'+defineId+'"><strong>部门名称：</strong></p></td>'
			HTML += '<td width="77%"><label><input type="text" data-type="lengthLimit" data-required="true" null-message="部门名称不能为空 ！" message="部门名称不允许超过60个字符！" data-length="60" name="department.name" class="input_cls" value="'+ department +'"></label></td></tr>';
			//上级部门
			if(fatherDept==="0"){
				HTML += '<tr><td><input type="hidden" name="fatherDepartmentId" value="0" /></td></tr>';
			}else{
				HTML += '<tr><td><p>上级部门：</p></td><td>'+ departmentSelect +'</td></tr>';
			}
			//职位列表
			postArray.each(function(j,postEl){
				HTML += '<tr><td><p>职位'+ (j+1) +'：</p></td>'
				HTML += '<td><input class="input_cls" data-required="false" message="职位不允许超过60个字符！" data-type="lengthLimit" data-length="60"  name="department.positionList['+j+'].name" type="text" value="'+ $(postEl).text() +'"> ';
				HTML += '<input type="checkbox" value="Y" name="department.positionList['+j+'].isLeader" '+ ($(postEl).hasClass('zrr')?' checked':'') +'>&nbsp;是否为责任人';
				HTML += '<input type="hidden" value="'+$(postEl).next().text()+'" name="department.positionList['+j+'].positionId") />';
				if(j==postCount-1){
					HTML += ' <img class="addpost linkhand" src="<%=basePath%>images/add01.gif" width="14" height="14">';
				}
				HTML += '</td></tr>'
			});
			if(postCount===0){
				HTML += '<tr><td><p>职位'+ (++postCount) +'：</p></td>'
				HTML += '<td><input class="input_cls" data-required="false" message="职位不允许超过60个字符！" data-type="lengthLimit" data-length="60" name="department.positionList[0].name" type="text" value=""> ';
				HTML += '<input type="checkbox" name="department.positionList[0].isLeader" value="Y">是否为责任人';
				HTML += ' <img class="addpost linkhand" src="<%=basePath%>images/add01.gif" width="14" height="14">';
				HTML += '</td></tr>'
			}
			//底部 
			HTML += '</table>';
			HTML += '<div class="btnblock"><input class="btngreen01 linkhand" type="button" value="保存" onclick="update(this)"></div>';
			HTML += '</div></div>';
			HTML += '<div class="Popupfoot"><img src="<%=basePath%>images/Popupbg01_footer.png" width="550" height="15"></div></div>';
			var that = $.dialog({skin: false,content: HTML});
			var form = that.boxy.find('.cjxbm');
			$("[name*='fatherDepartmentId']",form).val(fatherDept);
			var submitBtn = that.boxy.find('.btnblock img');
			var addBtn = that.boxy.find('.addpost');
			addBtn.click(function(){
				var newTr = $(postItem.replace(/\{count\}/,++postCount).replace(/\{count-1\}/,postCount-1).replace(/\{count-1\}/,postCount-1)).appendTo(form);
				var lastTd = newTr.find('td:last');
				addBtn.appendTo(lastTd);
			});
		});
	});
}

function update(obj){
	var table = $(obj).parent().parent().children("table");
	var params=getParams(table);
	if(validateSubmit(table)){
		$.ajax({
		  url: "<%=basePath%>account/updateDepartmentSave",
		  type:"POST",
		  contentType:"application/x-www-form-urlencoded; charset=utf-8",
		  data:params,
		  dataType: 'text',
		  success: function(data) {
			 var jsonobj=eval('('+data+')');
			 if(jsonobj.state==='1'){
				 alert(jsonobj.result);
				 $.dialog.close();
				 window.location.reload();
			 }else if(jsonobj.state==='0'){
				 alert(jsonobj.result);
			 }
		  },
		  error: function(XMLHttpRequest, textStatus, errorThrown) {
				 alert("修改失败！");
		  }
		});
	}
}
function getParams(table){
	var params = "";
	var id = $("[name*='department.departmentId']",table).val();
	if(id){
		params+="departmentId="+id;
	}
	var fatherDeptid = $("[name*='fatherDepartmentId']",table).val();
	if(fatherDeptid){
		params+="&fatherDepartmentId="+fatherDeptid;
	}
	var name = $("[name='department.name']",table).val();
	if(name)
		params+="&name="+name;
	var fatherDepartment = $("[name='fatherDepartmentId']",table).val();
	if(fatherDepartment)
		params+="&fatherDepartmentId="+fatherDepartment;
	$("[name*='].name']",table).each(function(index){
		params+="&positionList["+index+"].name="+$(this).val();
		params+="&positionList["+index+"].positionIndex="+index;
		params+="&positionList["+index+"].departmentId="+id;
		params+="&positionList["+index+"].positionId="+$(this).next().next().val();
		//if($(this).next().attr("checked")==="checked"){
		if($(this).next().attr("checked")){
			params+="&positionList["+index+"].isLeader="+$(this).next().val();
		}
	});
	return params;
}
function create(obj){
	var div = $(obj).closest(".zzjg");
	if(validateSubmit(div)){
		$.ajax({
		  url: "<%=basePath%>account/createDepartmentSave",
		  type:"POST",
		  contentType:"application/x-www-form-urlencoded; charset=utf-8",
		  data:$('#form0').serialize(),
		  success: function(data) {
			 var jsonobj=eval('('+data+')');
			 if(jsonobj.state==='1'){
				 alert(jsonobj.result);
				 window.location.reload();
			 }else if(jsonobj.state==='0'){
				 alert(jsonobj.result);
			 }
		  },
		  error: function(XMLHttpRequest, textStatus, errorThrown) {
				 alert("创建失败！");
		  }
		});
	}
}
function validateSubmit(obj){
	var message = "";
	$("[data-required='true']",obj).each(function(){
		var value = $(this).val();
		if(!value){
			var nullMessage = $(this).attr("null-message");
			message+=nullMessage+"\n";
		}
	});
	$("[data-type='lengthLimit']",obj).each(function(){
		var limitLength = $(this).attr("data-length");
		var value =  $(this).val();
		if(value){
			if(value.length>limitLength){
				message+=$(this).attr("message")+"\n";
			}
		}
	});
	
	if(message){
		alert(message);
		return false;
	}else{
		return true;
	}
}
function deleteDept(deptId){
	if(deptId){
		$.ajax({
		  url: "<%=basePath%>account/deleteDepartment",
		  type:"GET",
		  contentType:"application/x-www-form-urlencoded; charset=utf-8",
		  data:"departmentId="+deptId,
		  success: function(data) {
			 var jsonobj=eval('('+data+')');
			 if(jsonobj.state==='1'){
				 alert(jsonobj.result);
				 window.location.reload();
			 }else if(jsonobj.state==='0'){
				 alert(jsonobj.result);
			 }
		  },
		  error: function(XMLHttpRequest, textStatus, errorThrown) {
				 alert("删除失败！");
		  }
		});
	}
}
String.prototype.replaceAll = function(search, replace){  
	 var regex = new RegExp(search.toString(), "g");  
	 return this.replace(regex, replace.toString());  
}
$(document).ready(function(){
	initForm();
	bindList();
});
</script>

<!--中间部分开始-->
<div class="main">
  <!-- 左侧 -->
  <jsp:include page="/WEB-INF/views/account/sidebar.jsp"/>
  <!-- /左侧 -->
  <!-- 核心内容区域 -->
	<div id="iaas_layout_content" class="rightblock">
    	<p class="shadow"></p>
    	<div class="content"><!--默认状态下引用样式ml60，展开后引用样式ml140-->
	      	<div class="mainblock">
	      	<form:form id="form0" method="POST" action="/account/createDepartmentSave" modelAttribute="department" cssClass="basic-form form-horizontal">
	        	<div class="tabA">
	          		<h1>组织架构</h1>
	        	</div>
	        	<div class="zzjg">
				          <table width="100%" border="0" cellpadding="0" cellspacing="0" class="mt25">
				            <tr>
				              <td width="7%"><p><strong>部门名称：</strong></p></td>
				              <td width="93%"><label>
				              	  <form:input path="name"  class="input_cls" data-type="lengthLimit" data-required="true" data-length="60" null-message="部门名称不能为空 ！" message="部门名称不允许超过60个字符！"/>
				                </label></td>
				            </tr>
				            <tr>
				              <td><p>上级部门：</p></td>
				              <td class="departmenu_td">
				              	<form:select path="fatherDepartmentId" data-required="true" class="input_cls" null-message="部门名称不能为空 ！">
				              		<c:forEach items="${allDepartmentList}" var="depart">
				              			<option value="${depart.departmentId}">${depart.name}</option>
				              		</c:forEach>
				              	</form:select>
				              </td>
				            </tr>
				            <tr>
				              <td><p>职位1：</p></td>
				              <td>
				              	<form:input path="positionList[0].name"  class="input_cls" data-required="false" data-type="lengthLimit" data-length="60" message="职位不允许超过60个字符！"/>
				                <input type="checkbox" name="positionList[0].isLeader" value="Y" >
				                <input type="hidden" name="positionList[0].positionIndex" value="0" >
				                	是否为责任人</td>
				            </tr>
				            <tr>
				              <td><p>职位2：</p></td>
				              <td><form:input path="positionList[1].name"  class="input_cls" data-required="false" data-type="lengthLimit" data-length="60" message="职位不允许超过60个字符！"/>
				                <input type="checkbox" name="positionList[1].isLeader" value="Y">
				                <input type="hidden" name="positionList[1].positionIndex" value="1" >
				                	是否为责任人</td>
				            </tr>
				            <tr>
				              <td><p>职位3：</p></td>
				              <td><form:input path="positionList[2].name"  class="input_cls" data-required="false" data-type="lengthLimit" data-length="60" message="职位不允许超过60个字符！"/>
				                <input type="checkbox" name="positionList[2].isLeader" value="Y"> 是否为责任人 
				                <input type="hidden" name="positionList[2].positionIndex" value="2" >
				                <span class="addpost linkhand"><img src="<%=basePath%>images/add01.gif" width="14" height="14"></span></td>
				            </tr>
				          </table>
				          <div class="btn_cjxbm mt25"> 
				          		<a href="javascript:void(0)" onclick="create(this)"><img src="<%=basePath%>images/cj.png" width="24" height="24" border="0">创建新部门</a> 
				          		<a href="<%=basePath%>account/department"><img src="<%=basePath%>images/zzjg.png" width="21" height="21">返回组织架构图</a> 
				          </div>
				          <div class="clear"></div>
		         </div>
		   </form:form>      
		         <table width="100%" border="0" cellpadding="0" cellspacing="0" class="cjbm mt10">
		         	  <c:forEach items="${allDepartmentList}" var="department2" varStatus="stats">
		         	  <c:if test="${stats.index%2==0}">
			          <tr>
			            <td><p class="first_line">${department2.name}</p>
			              <p class="second_line"><span><a href="javascript:void(0)" class="editbtn">修改</a> | <a href="javascript:void(0)" onclick="deleteDept('${department2.departmentId}')">删除</a></span><span>创建时间：<fmt:formatDate value="${department2.createDate}" type="date" pattern="yyyy-MM-dd"/></span>
			              	<div style="display:none" class="defineId">${department2.departmentId}</div>
			              	<div style="display:none" class="fatherDept">${department2.fatherDepartmentId}</div>
			              	<div class="post_list">
			              	职位：
			              	<c:forEach items="${department2.positionList}" var="position" varStatus="stats">
			              		<c:if test="${position.isLeader=='Y'}">
			              		<b class="zrr">${position.name}</b>
			              		</c:if>
			              		<c:if test="${position.isLeader!='Y'}">
			              		<b >${position.name}</b>&nbsp;&nbsp;&nbsp;
			              		</c:if>
			              		<div style="display:none">${position.positionId}</div>
			              	</c:forEach>
			              	</div>
			              </p>
			            </td> 	
			          </tr>
			          </c:if>
			          <c:if test="${stats.index%2==1}">
			          <tr class="cjbm_bg">
		          	  		  <td><p class="first_line">${department2.name}</p>
				              <p class="second_line"><span><a href="javascript:void(0)" class="editbtn">修改</a> | <a href="javascript:void(0)" onclick="deleteDept('${department2.departmentId}')">删除</a></span><span>创建时间：<fmt:formatDate value="${department2.createDate}" type="date" pattern="yyyy-MM-dd"/></span>
				              	<div style="display:none" class="defineId">${department2.departmentId}</div>
			              		<div style="display:none" class="fatherDept">${department2.fatherDepartmentId}</div>
				              	<div class="post_list">
				              	职位：
				              	<c:forEach items="${department2.positionList}" var="position" varStatus="stats">
				              		<c:if test="${position.isLeader=='Y'}">
				              		<b class="zrr">${position.name}</b>
				              		</c:if>
				              		<c:if test="${position.isLeader!='Y'}">
				              		<b >${position.name}</b>&nbsp;&nbsp;&nbsp;
				              		</c:if>
				              		<div style="display:none">${position.positionId}</div>
				              	</c:forEach>
				              	</div>
				              </p>
			            </td> 	
		          	  </tr>
			          </c:if>
			          </c:forEach>
			     </table>
	      	</div>  
    	</div>
  	</div>
</div>
<!--中间部分结束-->
<!--底部开始-->
<jsp:include page="/WEB-INF/views/layouts/footer.jsp"/>
<!--底部结束-->

</body>
</html>
